<!doctype html>
<html>
<head>
    <meta charset=utf-8>
    <link rel="icon shortcut" href=img/logo.png type=image/png>
    <link rel=apple-touch-icon href=img/logo.png>
    <link rel=stylesheet href=lib/bootstrap-4.0.0-dist/css/bootstrap.min.css>
    <link rel=stylesheet href=css/base.css>
    <link rel=stylesheet href=css/ui-block.css>
    <meta name=viewport content="width=device-width">
    <title>NEBULAS</title>
</head>
<style>
    .qr_code>div {
        display: inline-block;
    }

    .qr_code>.display-none {
        display: none;
    }

    .transaction {
        margin-top: 1rem;
        display: none;
    }
</style>
<body>
    <div class=logo-main></div>
    <div class=header></div>
    <div class="container select-wallet-file"></div>

    <div id=walletinfo class="container transaction">
        <div class=row>
            <div class=col>
                <div class=form-group>
                    <label for=address data-i18n=wallet-info/your-addr>Your Address</label>
                    <input type=text class=form-control id=address disabled>
                </div>
                <div class=form-group>
                    <label for=amount_container data-i18n=wallet-info/acc-balance>Account Balance : </label>
                    <div id=amount_container class=number-comma data-disabled data-id=amount data-unit=currency data-currency-selector></div>
                </div>
                <div class=form-group>
                    <label for=keystore>
                        <span data-i18n=keystore-file>Keystore File</span>
                        (JSON / Recommended / Encrypted)
                    </label>
                    <button type=submit class="btn btn-default col-xs-12 col-sm-12 col-md-12 text-center" id=keystore data-i18n=download>Download</button>
                </div>
                <div class=form-group>
                    <label for=password data-i18n=wallet-info/private-key>Private Key (unencrypted)</label>
                    <input type=password id=password class=form-control disabled>
                    <div>
                        <input id=togglePassword type=checkbox>
                        <label for=togglePassword>visible</label>
                    </div>
                </div>
            </div>
            <div class="col qr_code">
                <div class=text-center>
                    <label for=addressqr data-i18n=wallet-info/your-addr>Your Address</label>
                    <div class=form-group id=addressqr></div>
                </div>
                <div class="display-none key_qr text-center">
                    <label for=privateqr data-i18n=wallet-info/private-key>Private Key (unencrypted)</label>
                    <div class=form-group id=privateqr></div>
                </div>
            </div>
        </div>
    </div>

    <div class=footer></div>

    <script src=lib/jquery-3.3.1.min.js></script>
    <script src=lib/bootstrap-4.0.0-dist/js/bootstrap.bundle.min.js data-depends=jquery.slim></script>
    <script src=lib/jquery.qrcode.min.js data-depends=jquery></script>
    <script src=lib/bootbox.min.js data-depends="bootstrap jquery.slim"></script>
    <script src=lib/Blob.js></script>
    <script src=lib/FileSaver.min.js></script>
    <script src=lib/nebulas.js></script>
    <script src=js/1-localSave.js></script>
    <script src=js/home.v1.js></script>
    <script src=js/i18n.js data-depends=jquery.slim></script>
    <script src=js/ui-block.js data-depends="bootbox blockies jquery.slim i18n.js nebulas.js"></script>
    <script>
        "use strict";

        var nebulas = require("nebulas"),
            Account = nebulas.Account,
            Neb = nebulas.Neb,
            Transaction = nebulas.Transaction,
            Utils = nebulas.Utils,
            neb = new Neb(),
            gAccount, gFileJson;

        neb.setRequest(new nebulas.HttpRequest(localSave.getItem("apiPrefix") || "https://testnet.nebulas.io/"));
        $("#keystore").on("click", onClickKeystore);
        $("#togglePassword").on("change", onChangeTogglePassword);

        uiBlock.insert({
            footer: ".footer",
            header: ".header",
            logoMain: ".logo-main",
            numberComma: ".number-comma",
            selectWalletFile: [".select-wallet-file", onUnlockFile]
        });

        function onCurrencyChanged() {
            updateBalance()
        }
        uiBlock.addCurrencyChangedListener(onCurrencyChanged);

        function onUnlockFile(swf, fileJson, account, password) {
            try {
                gAccount = account;
                gFileJson = fileJson;
                account.fromKey(fileJson, password);

                $("#address").val(account.getAddressString());
                $("#sideaddress").text(account.getAddressString());
                $("#password").val(account.getPrivateKeyString());
                $("#addressqr").html('').qrcode(account.getAddressString());
                $("#privateqr").html('').qrcode(account.getPrivateKeyString());
                $("#walletinfo").show();

                updateBalance();
            } catch (e) {
                // this catches e thrown by nebulas.js!account

                bootbox.dialog({
                    backdrop: true,
                    onEscape: true,
                    message: localSave.getItem("lang") == "en" ? e : "keystore 文件错误, 或者密码错误",
                    size: "large",
                    title: "Error"
                });
            }
        }

        function updateBalance() {
            if (!gAccount) {
                return;
            }
            var addr = gAccount.getAddressString();
            var currency = uiBlock.currency;
            var contractAddr = uiBlock.getContractAddr(uiBlock.currency);
            $("#amount").val("").trigger("input");
            if (currency == "NAS") {
                neb.api.getAccountState(addr)
                    .then(function (resp) {
                        if (currency != uiBlock.currency) {
                            return;
                        }
                        if (resp.error) {
                            throw new Error(resp.error);
                        }
                        var nas = nebulas.Unit.fromBasic(resp.balance, "nas").toString(10);
                        $("#amount").val(nas).trigger("input"); // add comma & unit from value, needs trigger 'input' event if via set o.value
                    })
                    .catch(function (e) {
                        if (currency != uiBlock.currency) {
                            return;
                        }
                        // this catches e thrown by nebulas.js!neb
                        bootbox.dialog({
                            backdrop: true,
                            onEscape: true,
                            message: i18n.apiErrorToText(e.message),
                            size: "large",
                            title: "Error"
                        });
                    });
            } else {
                var contract = {"function": "balanceOf", "args": "[\"" + addr + "\"]"};
                neb.api.call({"from": addr, "to": uiBlock.getContractAddr(uiBlock.currency), "gasLimit": 200000, "gasPrice":1000000, "value": 0, "contract": contract})
                    .then(function (resp) {
                        if (currency != uiBlock.currency) {
                            return;
                        }
                        if (resp.error) {
                            throw new Error(resp.error);
                        }
                        var b = resp.result.replace(/"/ig, "");
                        var balance = nebulas.Unit.fromBasic(b, "nas").toString(10)
                        $("#amount").val(balance).trigger("input"); // add comma & unit from value, needs trigger 'input' event if via set o.value
                    })
                    .catch(function (e) {
                        if (currency != uiBlock.currency) {
                            return;
                        }
                        // this catches e thrown by nebulas.js!neb
                        bootbox.dialog({
                            backdrop: true,
                            onEscape: true,
                            message: i18n.apiErrorToText(e.message),
                            size: "large",
                            title: "Error"
                        });
                    });
            }
        }

        function onClickKeystore() {
            var blob = new Blob([JSON.stringify(gFileJson)], { type: "application/json; charset=utf-8" });
            saveAs(blob, gAccount.getAddressString());
        }

        function onChangeTogglePassword(e) {
            if (e.target.checked) {
                $("#password").prop("type", "text");
                $(".key_qr").removeClass("display-none");
            } else {
                $("#password").prop("type", "password");
                $(".key_qr").addClass("display-none");
            }
        }
    </script>
</body>
</html>